<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>async与await结合发送 AJAX 请求</title>
</head>
<body>
    <button>点击获取段子</button>

    <script>
        // await promise 对象
        function sendAJAX(method, url){
            //返回 promise 对象
            return new Promise((resolve, reject) => {
                //
                let x = new XMLHttpRequest();
                //设置响应体结果
                x.responseType = 'json';
                //
                x.open(method, url);
                //
                x.send();
                //绑定事件
                x.onreadystatechange = function(){
                    if(x.readyState === 4){
                        if(x.status >= 200 && x.status < 300){
                            //成功
                            resolve({
                                status: x.status, //状态码
                                statusText: x.statusText, //状态字符串
                                headers: x.getAllResponseHeaders(), //响应头
                                data: x.response //响应体
                            });
                        }else{
                            //失败
                            reject({
                                status: x.status,
                                statusText: x.statusText,
                                message: '请求失败~~'
                            });
                        }
                    }
                }
            });
        }
    
        //获取按钮
        let btn = document.querySelector('button');

        //绑定事件 『重中之重, 必须要掌握』
        btn.onclick = async function(){
            try{
                //发送请求
                let res = await sendAJAX('get', 'http://api.xiaohigh.com/duanzi');
                //处理响应的结果
                console.log(res); //{status, statusText, headers, data}
            }catch(e){
                //输出
                console.error(`请求失败, 状态码为:`); 
                console.error(e)
            }
        }   
        
        
    </script>

</body>
</html>